package phase01.module1.code;

/**
 * 编程题<br>
 * 自定义数组扩容规则，当已存储元素数量达到总容量的 80%时，扩容 1.5 倍。<br>
 * 例如，总容量是 10，当输入第 8 个元素时，数组进行扩容，容量从 10 变 15。
 */
public class ArrayGrowth {

    private static class AutoGrowthArray {
        private int[] array;
        private int size = 0;

        public AutoGrowthArray(int initSize) {
            array = new int[initSize];
        }

        public int getSize() {
            return size;
        }

        public void insert(int pos, int val) {
            if (pos < 0 || pos > size) throw new ArrayIndexOutOfBoundsException();
            if (((size * 1.0) / array.length) >= 0.8) {
                int newLength = (int) (array.length * 1.5);
                System.out.println("插入第" + (size + 1) + "个数,数组从" + array.length + "增加到" + newLength);
                int[] newArray = new int[newLength];
                System.arraycopy(array, 0, newArray, 0, size);
                array = newArray;
            }
            System.arraycopy(array, pos, array, pos + 1, size - pos);
            array[pos] = val;
            size += 1;
        }
    }

    public static void main(String[] args) {
        AutoGrowthArray autoGrowthArray = new AutoGrowthArray(10);
        for (int i = 0; i < 100; i++) {
            autoGrowthArray.insert(autoGrowthArray.getSize(), i + 1);
        }
    }
}
